package jeesample.service.publishers;

import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import jeesample.model.DumpInfo;

import org.apache.log4j.Logger;

public final class EchoServicePublisher extends BaseServicePublisher {
	private Logger logger = Logger.getLogger(getClass());

	@Override
	protected Logger logger() {
		return logger;
	}

	public String ping(final String userId) {
		dbg("ping:"+userId);
		String timeNow = new Date().toString();
		return "Ping service server time now:" + timeNow;
	}	

	public DumpInfo dump(final ServletContext context,
			final HttpServletRequest request) {
		dbg("dumping info begins.");
		DumpInfo info = new DumpInfo();
		info.setServerInfo(context.getServerInfo());
		List<String> servletList = new LinkedList<>();
		Enumeration<String> servletNames = context.getServletNames();
		while (servletNames.hasMoreElements()) {
			String servletName = servletNames.nextElement();
			servletList.add(servletName);
		}
		info.setServletList(servletList);
		info.setContextPath(context.getContextPath());
		info.setContextName(context.getServletContextName());
		List<String> paramList = new LinkedList<>();
		Enumeration<String> paramNames = context.getInitParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();
			String paramVal = context.getInitParameter(paramName);
			paramList.add(paramName + ":" + paramVal);
		}
		info.setParamList(paramList);

		String hostInfo = request.getLocalAddr() + ":" + request.getLocalPort();
		String clientInfo = request.getRemoteAddr() + ":"
				+ request.getRemotePort();

		info.setHostInfo(hostInfo);
		info.setClientInfo(clientInfo);
		info.setRequestPath(request.getPathInfo());
		info.setRequestMethod(request.getMethod());
		dbg("dumping info:"+info.toString());
		return info;
	}

	public DumpInfo dump(final WebServiceContext webContext) {		
		MessageContext msgCtx = webContext.getMessageContext();
		ServletContext context = (ServletContext) msgCtx
				.get(MessageContext.SERVLET_CONTEXT);
		HttpServletRequest request = (HttpServletRequest) msgCtx
				.get(MessageContext.SERVLET_REQUEST);

		return dump(context, request);
	}

}
